package com.xpengplayer.data;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 播放历史记录管理器
 * 负责管理最近播放记录的存储、检索和更新
 */
public class PlayHistoryManager {
    private static final String TAG = "PlayHistoryManager";
    private static final String PREF_NAME = "play_history";
    private static final String KEY_HISTORY_LIST = "history_list";
    private static final int MAX_HISTORY_COUNT = 50;  // 最多保存50条记录

    private SharedPreferences preferences;
    private Gson gson;

    public PlayHistoryManager(Context context) {
        this.preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        this.gson = new Gson();
    }

    /**
     * 获取所有播放历史记录
     * @return 按播放时间倒序排列的历史记录列表
     */
    public List<PlayHistory> getAllHistory() {
        String historyJson = preferences.getString(KEY_HISTORY_LIST, "[]");
        Type type = new TypeToken<List<PlayHistory>>(){}.getType();
        List<PlayHistory> historyList = gson.fromJson(historyJson, type);

        // 按播放时间倒序排列
        if (historyList != null) {
            Collections.sort(historyList, new Comparator<PlayHistory>() {
                @Override
                public int compare(PlayHistory h1, PlayHistory h2) {
                    return Long.compare(h2.getLastPlayTime(), h1.getLastPlayTime());
                }
            });
        }

        return historyList != null ? historyList : new ArrayList<>();
    }

    /**
     * 添加或更新播放记录
     * @param history 播放记录对象
     */
    public void addOrUpdateHistory(PlayHistory history) {
        List<PlayHistory> historyList = getAllHistory();

        // 检查是否已存在相同路径的记录
        int existingIndex = -1;
        for (int i = 0; i < historyList.size(); i++) {
            if (historyList.get(i).getVideoPath().equals(history.getVideoPath())) {
                existingIndex = i;
                break;
            }
        }

        // 如果已存在，则先移除旧记录
        if (existingIndex != -1) {
            historyList.remove(existingIndex);
        }

        // 添加新记录到列表开头
        historyList.add(0, history);

        // 限制历史记录数量
        if (historyList.size() > MAX_HISTORY_COUNT) {
            historyList = historyList.subList(0, MAX_HISTORY_COUNT);
        }

        // 保存更新后的历史记录
        saveHistoryList(historyList);
    }

    /**
     * 根据视频路径查找历史记录
     * @param videoPath 视频路径
     * @return 找到的历史记录，未找到则返回null
     */
    public PlayHistory findHistoryByPath(String videoPath) {
        List<PlayHistory> historyList = getAllHistory();
        for (PlayHistory history : historyList) {
            if (history.getVideoPath().equals(videoPath)) {
                return history;
            }
        }
        return null;
    }

    /**
     * 清空所有历史记录
     */
    public void clearAllHistory() {
        preferences.edit().remove(KEY_HISTORY_LIST).apply();
    }

    /**
     * 删除单条历史记录
     * @param videoPath 要删除的视频路径
     */
    public void deleteHistory(String videoPath) {
        List<PlayHistory> historyList = getAllHistory();
        for (int i = 0; i < historyList.size(); i++) {
            if (historyList.get(i).getVideoPath().equals(videoPath)) {
                historyList.remove(i);
                saveHistoryList(historyList);
                break;
            }
        }
    }

    /**
     * 保存历史记录列表到SharedPreferences
     */
    private void saveHistoryList(List<PlayHistory> historyList) {
        String historyJson = gson.toJson(historyList);
        preferences.edit().putString(KEY_HISTORY_LIST, historyJson).apply();
    }
}